package com.finley.flowabledemo.plc.controller;

import com.finley.flowabledemo.plc.service.ModbusService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/modbus")
public class ModbusController {

    private final ModbusService modbusService;

    public ModbusController(ModbusService modbusService) {
        this.modbusService = modbusService;
    }

    /**
     * 读取线圈状态
     * @param address 起始地址
     * @param quantity 读取数量
     * @return 线圈状态列表
     */
    @GetMapping("/coils")
    public List<Boolean> readCoils(
            @RequestParam int address,
            @RequestParam(defaultValue = "1") int quantity) {
        return modbusService.readCoils(address, quantity);
    }

    /**
     * 读取保持寄存器(原始字节)
     * @param address 起始地址
     * @param quantity 读取数量
     * @return 寄存器字节数据
     */
    @GetMapping("/registers/bytes")
    public byte[] readHoldRegisters(
            @RequestParam int address,
            @RequestParam(defaultValue = "1") int quantity) {
        return modbusService.readHoldRegisters(address, quantity);
    }


    /**
     * 读取保持寄存器(16位有符号整数)
     * @param address 寄存器地址
     * @return 16位有符号整数
     */
    @GetMapping("/registers/int16")
    public short readInt16(@RequestParam int address) {
        return modbusService.readInt16(address);
    }

    /**
     * 读取保持寄存器(32位浮点数)
     * @param address 寄存器地址
     * @return 32位浮点数
     */
    @GetMapping("/registers/float32")
    public float readFloat32(@RequestParam int address) {
        return modbusService.readFloat32(address);
    }

    /**
     * 写入单个线圈
     * @param address 线圈地址
     * @param value 要写入的值
     */
    @PostMapping("/coils")
    public void writeCoil(
            @RequestParam int address,
            @RequestParam boolean value) {
        modbusService.writeCoil(address, value);
    }

    /**
     * 写入单个寄存器(16位有符号整数)
     * @param address 寄存器地址
     * @param value 要写入的值
     */
    @PostMapping("/registers/int16")
    public void writeInt16(
            @RequestParam int address,
            @RequestParam short value) {
        modbusService.writeInt16(address, value);
    }

    /**
     * 写入单个寄存器(32位浮点数)
     * @param address 寄存器地址
     * @param value 要写入的值
     */
    @PostMapping("/registers/float32")
    public void writeFloat32(
            @RequestParam int address,
            @RequestParam float value) {
        modbusService.writeFloat32(address, value);
    }
}